#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class GuizhouGygjgxqglwyh39d9Policy(BaseTaxPolicySpider):
    name = 'guizhou_gygjgxqglwyh_39d9_policy'

    province = '贵州省'
    city = '贵阳市'
    county = '贵阳国家高新区'
    park = ''
    source = '贵阳国家高新区管理委员会'
    url = 'https://www.guiyang.gov.cn/zwgk/gzhgfxwjsjk/gfxwjsjk/gxq_wnk/'
    headers = {
        "Content-Type": "application/json;charset=UTF-8",
    }

    def start_requests(self):
        # url = 'https://jr.guizhou.gov.cn/zwgk/gzhgfxwjsjk/gfxwjsjk/index.html'
        url = "https://www.guiyang.gov.cn/irs/front/list"
        data = {
            "tableName": "t_179d1430e47",
            "pageNo": 1,
            "pageSize": 10,
            "searchFields": [
                {
                    "fieldName": "f_202163381596",
                    "searchWord": "5871630"
                }
            ],
            "sorts": [
                {
                    "sortField": "save_time",
                    "sortOrder": "DESC"
                }
            ],
            "tenantId": "13",
            "isPage": True
        }
        # yield scrapy.Request(url, callback=self.parse_list)
        yield scrapy.Request(
            url,
            body=json.dumps(data, separators=(',', ':')),
            headers=self.headers,
            method="POST",
            callback=self.parse_list,
            meta={'data': data}
        )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.json()['data']['list']:
            item = Item()
            item['source_url'] = elem['doc_pub_url']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['save_time']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.html' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        data = response.meta.get('data')
        if response.meta.get("is_next") is not False:
            total_page = response.json()['data']['pager']['pageCount']
            for page_num in range(1, int(total_page) // 1 + 1):
                data['pageNo'] = page_num
                yield response.follow(response.url, method="POST", headers=self.headers, body=json.dumps(data, separators=(',', ':')),
                                      callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl guizhou_gygjgxqglwyh_39d9_policy".split())
